package com.design.marketPrj.application.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.base.oauth.models.AlipaySystemOauthTokenResponse;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.alipay.easysdk.util.generic.models.AlipayOpenApiGenericResponse;
import com.design.marketPrj.application.bean.PO.*;
import com.design.marketPrj.application.mapper.AppAuthMapper;
import com.design.marketPrj.application.mapper.PayHistoryMapper;
import com.design.marketPrj.application.mapper.TransferHistoryMapper;
import com.design.marketPrj.application.mapper.UserMapper;
import com.design.marketPrj.application.util.DateUtil;
import com.design.marketPrj.application.util.EncodeUtil;
import com.design.marketPrj.application.util.UUIDUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class PayService {

    @Autowired
    PayHistoryMapper payHistoryMapper;
    @Autowired
    TransferHistoryMapper transferHistoryMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AppAuthMapper appAuthMapper;

    public String payHistoryCreate(User user, BigDecimal payMoney){
        PayHistory payHistory = new PayHistory();
        payHistory.setId(UUIDUtils.getUUID());
        payHistory.setCreateTime(DateUtil.getTime());
        payHistory.setCreateUser(user.getId());
        payHistory.setPayMoney(payMoney);
        payHistory.setStatus(0);
        payHistoryMapper.insertSelective(payHistory);
        return payHistory.getId();
    }

    public String transferHistoryCreate(User user, BigDecimal transferMoney){
        //如果取款的金额小于账户的余额的话，则返回null，即不执行退款操作
        if(user.getMoney().compareTo(transferMoney)==-1){
            return null;
        }
        TransferHistory transferHistory = new TransferHistory();
        transferHistory.setId(UUIDUtils.getUUID());
        transferHistory.setCreateTime(DateUtil.getTime());
        transferHistory.setCreateUser(user.getId());
        transferHistory.setTransferMoney(transferMoney);
        transferHistory.setStatus(0);
        transferHistoryMapper.insertSelective(transferHistory);
        return transferHistory.getId();
    }

    public void paySuccess(String tradeNo,BigDecimal moneyToAdd){
        try {
            PayHistory payHistory = payHistoryMapper.selectByPrimaryKey(tradeNo);
            if(payHistory.getStatus()==0){
                User user = userMapper.selectByPrimaryKey(payHistory.getCreateUser());
                payHistory.setStatus(1);
                user.setMoney(user.getMoney().add(moneyToAdd));
                payHistoryMapper.updateByPrimaryKeySelective(payHistory);
                userMapper.updateByPrimaryKeySelective(user);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }

    public void transferSuccess(String tradeNo,BigDecimal moneyToTransfer){
        try {
            TransferHistory payHistory = transferHistoryMapper.selectByPrimaryKey(tradeNo);
            User user = userMapper.selectByPrimaryKey(payHistory.getCreateUser());
            payHistory.setStatus(1);
            user.setMoney(user.getMoney().subtract(moneyToTransfer));
            transferHistoryMapper.updateByPrimaryKeySelective(payHistory);
            userMapper.updateByPrimaryKeySelective(user);
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }


    /**
     * 对应alipay.trade.page.pay 接口
     * 构造交易数据供pc端到支付宝下单
     */
    public AlipayTradePagePayResponse createWebTradeForm(String subject ,String tradeNo,String totalAmount,String returnUrl) throws Exception{
        return Factory.Payment.Page()
                //单独设置超时时间 默认15分钟
                .optional("timeout_express","15m").asyncNotify(returnUrl)
                .pay(subject,tradeNo,totalAmount, returnUrl);
    }

    /**
     * 对应alipay.fund.trans.uni.transfer 接口
     * 创建一次转账
     */
    public AlipayOpenApiGenericResponse createTransferForm(String moneyToTrans,String transferNo,String identity) throws Exception{
        String product_code = "TRANS_ACCOUNT_NO_PWD";
        String identity_type = "ALIPAY_USER_ID";
        Map<String, String> textParams = new HashMap<>();
        Map<String, Object> bizParams = new HashMap<>();
        bizParams.put("out_biz_no", transferNo);
        bizParams.put("trans_amount", moneyToTrans);
        bizParams.put("product_code", product_code);
        bizParams.put("biz_scene", "DIRECT_TRANSFER");
        bizParams.put("order_title", "提现到账");
        JSONObject payeeInfoParams = new JSONObject();
        payeeInfoParams.put("identity", identity);
        payeeInfoParams.put("identity_type", identity_type);
        bizParams.put("payee_info", payeeInfoParams.toJSONString());
        return Factory.Util.Generic().execute(
                "alipay.fund.trans.uni.transfer", textParams, bizParams);

    }

    /**
     * 对应cloud.base.oauth.getToken 接口
     * 构造交易数据供pc端到支付宝下单
     * @return
     */
    public AlipaySystemOauthTokenResponse getToken(String authCode) throws Exception{
        return Factory.Base.OAuth().getToken(authCode);
    }

    /**
     * 对应alipay.user.info.auth 接口
     * 用户登录授权
     */
    public String userAuth(String uuid,String appId){
        String scopes = "auth_base";
        String returnUrl = "http://127.0.0.1:80/alipayAuthReturn";
        String url = "https://openauth.alipaydev.com/oauth2/publicAppAuthorize.htm?";
        url += "app_id="+ appId;
        url += "&scope=" + scopes;
        url += "&redirect_uri=" + EncodeUtil.urlEncode(returnUrl);
        url += "&state=" + uuid;
        return url;
    }

    public void userAuthSuccess(String appAuthId,String userId){
        User user = userMapper.selectByPrimaryKey(userId);
        user.setAliBind(true);
        userMapper.updateByPrimaryKeySelective(user);
        AppAuth appAuth = new AppAuth();
        appAuth.setId(UUIDUtils.getUUID());
        appAuth.setUserId(userId);
        appAuth.setAppAuthId(appAuthId);
        appAuthMapper.insertSelective(appAuth);
    }

    public String getAuthCode(String userId){

        String authCode = null;
        try{
            AppAuthExample appAuthExample = new AppAuthExample();
            appAuthExample.or().andUserIdEqualTo(userId);
            authCode = appAuthMapper.selectByExample(appAuthExample).get(0).getAppAuthId();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return authCode;
    }





}
